import * as fs from 'fs-extra';
import * as path from 'path';
import { Novel } from './models/novel';
import { Chapter } from './models/chapter';
import { config } from './config';

export class Storage {
  private basePath: string;
  
  constructor(basePath: string = config.storage.basePath) {
    this.basePath = basePath;
    fs.ensureDirSync(this.basePath);
  }

  async saveNovel(novel: Novel): Promise<void> {
    const novelDir = path.join(this.basePath, this.sanitizePath(novel.title));
    fs.ensureDirSync(novelDir);
    await fs.writeJson(path.join(novelDir, 'info.json'), novel, { spaces: 2 });
    const chaptersDir = path.join(novelDir, 'chapters');
    fs.ensureDirSync(chaptersDir);
    console.log(`小说《${novel.title}》信息已保存`);
  }

  async saveChapter(chapter: Chapter, novelTitle: string): Promise<void> {
    const novelDir = path.join(this.basePath, this.sanitizePath(novelTitle));
    const chaptersDir = path.join(novelDir, 'chapters');
    const fileName = `${String(chapter.index).padStart(4, '0')}-${this.sanitizePath(chapter.title)}.txt`;
    const filePath = path.join(chaptersDir, fileName);
    const textContent = chapter.content;
    await fs.writeFile(filePath, textContent);
    const infoPath = path.join(novelDir, 'info.json');
    const novelInfo = await fs.readJson(infoPath);
    if (!novelInfo.chapters) {
      novelInfo.chapters = [];
    }
    novelInfo.chapters.push({
      index: chapter.index,
      title: chapter.title,
      fileName: fileName
    });
    await fs.writeJson(infoPath, novelInfo, { spaces: 2 });
    console.log(`章节《${chapter.title}》已保存`);
  }

  private sanitizePath(input: string): string {
    return input.replace(/[\\/:*?"<>|]/g, '_');
  }
}